package goTool

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"log"
	"os"
)

type ZOss struct {
	Endpoint        string
	AccessKeyId     string
	AccessKeySecret string
	Bucket          string
	client          *oss.Client
}

func (zo *ZOss) InitOss() {
	client, err := oss.New(zo.Endpoint, zo.AccessKeyId, zo.AccessKeySecret)
	if err != nil {
		log.Fatalf("Init Oss Client Error %v", err)
	}
	zo.client = client
}

// Notice: Upload localFile to Aliyun Oss, multipart upload unit 100*1024 k
// Duthor: zhaoce
// Date: 2018/03/16
func (zo *ZOss) Upload(object, sourceFile string) {
	if _, err := os.Open(sourceFile); err != nil {
		return
	}

	bucket, err := zo.client.Bucket(zo.Bucket)
	if err != nil {
		return
	}
	err = bucket.UploadFile(object, sourceFile, 100*1024, oss.Checkpoint(true, ""))
	if err != nil {
		return
	}
}

// Notice: Delete Aliyun Oss File, support multi files
// Duthor: zhaoce
// Date: 2018/03/16
func (zo *ZOss) DeleteObjects(object []string) {
	bucket, err := zo.client.Bucket(zo.Bucket)
	if err != nil {
		return
	}

	deleteObjects := make([]string, 0)
	for _, v := range object {
		isExist, err := bucket.IsObjectExist(v)
		if err != nil {
			return
		}

		if isExist {
			deleteObjects = append(deleteObjects, v)
		}
	}

	_, err = bucket.DeleteObjects(deleteObjects)
	if err != nil {
		return
	}
	//(verbose)mode or simple(quiet)mode，default verbose mode
	oss.DeleteObjectsQuiet(true)
}
